#*-*coding:utf8*-*#
__author__ = 'guo'
from .models import *
from app.customer.models import *
from django.shortcuts import render

import smtplib,base64
from email.mime.text import MIMEText
from email.header import Header
from email.utils import parseaddr, formataddr
from libs.Base import *
from django.contrib.auth.hashers import make_password, check_password
from django.contrib.auth import decorators

# Create your views here.
# 发送邮件列表
@decorators.login_required(login_url="/crm/login/")
def index(request):
    return render(request, 'market/index.html', locals())



# 邮件设置
@decorators.login_required(login_url="/crm/login/")
def EmailSet(request):
    if request.method == "POST":
        EC = {}
        EC["smtp_address"] = request.POST.get("smtp_address")
        EC["smtp_port"] = request.POST.get("smtp_port")
        EC["smtp_email"] = request.POST.get("smtp_email")
        EC["smtp_user"] = request.POST.get("smtp_user")
        EC["smtp_pwd"] = request.POST.get("smtp_password")
        try:
            server = smtplib.SMTP(EC["smtp_address"], timeout=20)
            server.set_debuglevel(0)
        except Exception as e:
            return OutJson(300, "连接失败")
        try:
            server.login(EC["smtp_email"], EC["smtp_pwd"])
        except smtplib.SMTPAuthenticationError as e:
            return OutJson(300, "登录失败,请确认你的用户名和密码")

        ECjson = base64.b64encode(json.dumps(EC).encode("utf-8"))
        ResultEc = EConfig.objects.filter(ke="email",uid=request.user.id)
        if ResultEc:
            if ResultEc.update(val=ECjson):
                return OutJson(200,"操作成功")
            else: return OutJson(300, "操作失败")
        else:
            if EConfig.objects.create(ke="email", uid=request.user.id, val = ECjson, type=1):
                return OutJson(200,"操作成功")
            else: return OutJson(300, "操作失败")
    else:
        econfig = EConfig.objects.filter(uid=request.user.id)
        if len(econfig)>0:
            ecdict = json.loads(econfig[0].val)
        else:
            ecdict = {}
        return render(request, 'market/email-set.html', locals())


# 邮件模板设置
@decorators.login_required(login_url="/crm/login/")
def EmailTempSet(request):
    if request.POST.get("dosubmit"):
        moban = request.GET.get("moban")
    else:
        return render(request, 'market/email-temp-set.html', locals())

# 邮件发送
@decorators.login_required(login_url="/crm/login/")
def EmailSend(request):
    if request.method == "POST":
        cgroup = request.POST.getlist("cgroup")
        FromTitle = request.POST.get("FromTitle")
        ToTitle = ""
        EmailTitle = request.POST.get("title")
        EmailContent = request.POST.get("content")

        emaillist = []
        for x in cgroup:
            #选择所有的客户
            if x == "all":
                customerlist = Customer.objects.filter(saler_id = request.user.id)
                for customer in customerlist:
                    emaillist.append(customer.email)
                break
            #选择分组进行发送
            else:
                customerlist = Customer.objects.filter(groupid=x)
                for customer in customerlist:
                    emaillist.append(customer.email)
        if len(emaillist) > 0:
            return OutJson(300,"此客户组下没有客户")
        if Send(emaillist, FromTitle, ToTitle,EmailTitle,EmailContent, request) == True:
            return OutJson(200, "发送成功")
        else:
            return OutJson(300,"发送失败")
    else:
        customer = CustomerGroup.objects.filter(ofsaleid=request.user.id)
        return render(request, 'market/email-send.html', locals())


# 获取收件人列表
@decorators.login_required(login_url="/crm/login/")
def Emaillist(request):
    return render(request, "market/email-list.html", locals())


# 批量发送邮件 涵数
def Send(list, FromTitle, ToTitle, title,content, req):
        user = EConfig.objects.filter(uid=req.user.id)
        # base64String = user[0].val
        jsondict = json.loads(base64.b64decode(user[0].val).decode())

        msg = MIMEText(content, _subtype='html', _charset='utf-8')
        msg['From'] = format_addr(FromTitle + '<%s>' % jsondict["smtp_email"])
        server = smtplib.SMTP(jsondict["smtp_address"], 25)
        server.set_debuglevel(0)

        try:
            server.login(jsondict["smtp_email"], jsondict["smtp_pwd"])
            SendLogList = []
            for email in list:
                msg['To'] =  email
                msg['Subject'] = Header(title, 'utf-8').encode()
                server.sendmail(jsondict["smtp_email"], email, msg.as_string())
                SendLogList.append(
                    SendEmailLog(
                        fuid = req.user.id,
                        fromtitle = FromTitle,
                        totitle = ToTitle,
                        femail =jsondict["smtp_email"],
                        temail=email,
                        title=title,
                        content=content
                    )
                )
            #批量写入表日志
            SendEmailLog.objects.bulk_create(SendLogList)
            server.quit()
            return True
        except Exception as e:
            print(e)
            return False


def format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))
